package net.sashag.nadlandroid;

import java.util.List;

import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseQuery.CachePolicy;

public class Region {

	private String name;
	private ParseGeoPoint northEast;
	private ParseGeoPoint southWest;
	
	private Region(ParseObject regionObject) {
		name = regionObject.getString("Name");
		northEast = regionObject.getParseGeoPoint("NorthEast");
		southWest = regionObject.getParseGeoPoint("SouthWest");
	}
	
	public String getName() {
		return name;
	}
	public ParseGeoPoint getNorthEast() {
		return northEast;
	}
	public ParseGeoPoint getSouthWest() {
		return southWest;
	}
	
	@Override
	public String toString() {
		return name;
	}
	
	public static Region fromName(String name) throws ParseException {
		ParseQuery query = new ParseQuery("Region");
		query.setCachePolicy(CachePolicy.CACHE_ELSE_NETWORK);
		query.setMaxCacheAge(24*60*60*1000 /*one day*/);
		query.whereEqualTo("Name", name);
		ParseObject regionObject = query.getFirst();
		if (regionObject == null)
			return null;
		return new Region(regionObject);
	}
	
	public static Region[] getAllRegions() throws ParseException {
		ParseQuery query = new ParseQuery("Region");
		query.setCachePolicy(CachePolicy.CACHE_ELSE_NETWORK);
		query.setMaxCacheAge(24*60*60*1000 /*one day*/);
		List<ParseObject> regionObjects = query.find();
		Region[] regions = new Region[regionObjects.size()];
		for (int i = 0; i < regionObjects.size(); ++i) {
			Region region = new Region(regionObjects.get(i));
			regions[i] = region;
		}
		return regions;
	}
	
}
